package com.file.choose.montaro;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Parcelable;
import android.os.StrictMode;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast;

import java.io.File;
import java.security.Permission;

import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import static android.content.Context.MODE_WORLD_READABLE;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;

public class MainActivity extends Activity {
    AlertDialog.Builder AB=null;
    EditText ET=null;
    int option=0;
    int tmpOption=0;
    String moveDir=null;
    RadioGroup RG=null;
    final String[] Items={"不操作","移动文件","删除文件(不推荐)"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RG=findViewById(R.id.radio_group);
        Init();
        createListener();
        checkReadPermission();
        isDefaultApp();
    }
    public void button_capture_OnClick(View v){
       Intent I= new Intent("android.media.action.IMAGE_CAPTURE");
       File outputName= new File(Environment.getExternalStorageDirectory()+"/"+System.currentTimeMillis()+".jpg");
       Object localObject=Uri.fromFile(outputName);
       I.putExtra("output", (Parcelable) localObject);
       startActivityForResult(I,1024);
    }
    public void button_system_camera_OnClick(View v){
        Intent I= new Intent("android.media.action.IMAGE_CAPTURE");
        File outputName= new File(Environment.getExternalStorageDirectory()+"/"+System.currentTimeMillis()+".jpg");
        Object localObject=Uri.fromFile(outputName);
        I.setComponent(new ComponentName("com.huawei.camera","com.huawei.camera.controller.ThirdCameraActivity"));
        I.putExtra("output", (Parcelable) localObject);
        startActivityForResult(I,210);
    }
    public void button_save_OnClick(View v){
        ET=findViewById(R.id.edit_default_dir);
        String path=ET.getText().toString();
        if(!new File(path).exists()){
            Toast.makeText(this,"设定默认目录有误,请确定目录是否存在！",Toast.LENGTH_SHORT).show();
            return;
        }
        if(!path.substring(path.length()-1,path.length()).equals("/"))
            path+="/";
        setData("CurrentPath",path);
        ET=findViewById(R.id.edit_move_dir);
        path=ET.getText().toString();
        setData("moveDir",path);
        switch(RG.getCheckedRadioButtonId()){
            case R.id.radio_button_none:
                setData("option","none");
                break;
            case R.id.radio_button_move:
                setData("option","move");
                if(path.equals("")){
                    path=Environment.getExternalStorageDirectory().getPath()+"/backupFile/";//默认路径
                    new File(path).mkdirs();
                }
                if(!new File(path).exists()){
                    Toast.makeText(MainActivity.this,"设定移动目录有误,请确定目录是否存在！",Toast.LENGTH_SHORT).show();
                    return;
                }
                break;
            case R.id.radio_button_dele:
                setData("option","dele");
                break;
            default:
                setData("option","none");
                break;
        }
        Toast.makeText(MainActivity.this,"保存完成",Toast.LENGTH_SHORT).show();
    }
    @Override
    public void onActivityResult(int requestCode,int resultCode,Intent data){
        if(resultCode==RESULT_OK)
        {
            Toast.makeText(this,"Intent OK",Toast.LENGTH_SHORT).show();
        }
        else
            Toast.makeText(this,"Intent CANCELED",Toast.LENGTH_SHORT).show();
        super.onActivityResult(requestCode,resultCode,data);
    }

    private void checkReadPermission() {
        int PERMISSION=3211;
        if(Build.VERSION.SDK_INT<23)
            return ;
        if (ContextCompat.checkSelfPermission(MainActivity.this, READ_EXTERNAL_STORAGE) == PERMISSION_GRANTED) {
            Log.i("Perimission Read","YES!");
        } else {
            Log.i("Perimission Read","NO!");
            Toast.makeText(this,"没有存储权限！",Toast.LENGTH_SHORT).show();
            ActivityCompat.requestPermissions(this,new String[]{READ_EXTERNAL_STORAGE,WRITE_EXTERNAL_STORAGE},PERMISSION);
        }
        if(ContextCompat.checkSelfPermission(MainActivity.this, WRITE_EXTERNAL_STORAGE) != PERMISSION_GRANTED){
            Log.i("Perimission Write","NO!");
            ActivityCompat.requestPermissions(this,new String[]{READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE},PERMISSION);
        }
    }
    public void Button_ChangeDir(View v) {
        final EditText et=new EditText(this);
        //et.
        et.setText(getData("CurrentPath"));
        new AlertDialog.Builder(this)
                .setTitle("设定默认目录:")
                .setView(et)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        String newPath=et.getText().toString();
                        File f=new File(newPath);
                        if((!f.exists())||f.isFile()) {
                            Toast.makeText(
                                    MainActivity.this,
                                    "路径不正确！请重新输入！",
                                    Toast.LENGTH_SHORT
                            ).show();
                            return;
                        }
                        if(!newPath.substring(newPath.length()-1,newPath.length()).equals("/"))
                            newPath+="/";
                        setData("CurrentPath",newPath);
                        Log.i("* * * Set Current Path:",et.getText().toString());
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                })
                .show();
    }

    public void Button_SetDefaultOperation(View v){
        AB=new AlertDialog.Builder(this);
        AB.setCancelable(false);
        ET=new EditText(this);
        ET.setText(moveDir);
        AB.setTitle("选择操作");
        AB.setSingleChoiceItems(
           Items,
           option,
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    tmpOption=i;
                }
            }
        );
        AB.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                //option=tmpOption;
                switch(tmpOption)
                {
                    case 0:
                        option=0;
                        setData("option","none");
                        break;
                    case 1:
                        AB=new AlertDialog.Builder(MainActivity.this);
                        AB.setTitle("移动到:");
                        AB.setView(ET);
                        AB.setPositiveButton("确定",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    String tmpPath=ET.getText().toString();
                                    File f=new File(tmpPath);
                                    f.mkdirs();
                                    if(!f.exists()||f.isFile()){
                                        Toast.makeText(
                                                MainActivity.this,
                                                "路径不正确！请重新输入！",
                                                Toast.LENGTH_SHORT
                                        ).show();
                                        return;
                                    }
                                    moveDir=tmpPath;
                                    setData("moveDir",moveDir);
                                    option=1;
                                    setData("option","move");
                                }
                            }
                        );
                        AB.setNegativeButton("取消",null);
                        AB.show();
                        break;
                    case 2:
                        option=2;
                        setData("option","dele");
                        break;
                    default:
                        option=0;
                }
            }
        });
        AB.setNegativeButton("取消",null);
        AB.show();
    }
    public String getData(String Key){
        SharedPreferences sp=this.getSharedPreferences("Data", MODE_PRIVATE);
        return sp.getString(Key,"");
    }
    public void setData(String Key,String Data){
        SharedPreferences sp=this.getSharedPreferences("Data", MODE_PRIVATE);
        SharedPreferences.Editor ed=sp.edit();
        ed.putString(Key,Data);
        ed.apply();
    }
    public boolean isDefaultApp(){
        Intent I=new Intent("android.media.action.IMAGE_CAPTURE");
        //I.putExtra("output",Uri.fromFile(new File()))
        PackageManager pm=MainActivity.this.getPackageManager();
        ResolveInfo RI=pm.resolveActivity(I,PackageManager.MATCH_DEFAULT_ONLY);
        Log.i("* * * * * Default:","Info "+RI+"PackageName"+RI.activityInfo.packageName);
        Log.i("PackageName",getPackageName());
        if(!RI.activityInfo.packageName.equals(getPackageName())){
            Toast.makeText(MainActivity.this,"当前应用不是默认应用!",Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }
    public void Init(){
        if(Build.VERSION.SDK_INT>=18){
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
            builder.detectFileUriExposure();
        }
        if(getData("CurrentPath").equals(""))
            setData("CurrentPath",Environment.getExternalStorageDirectory().getPath() + "/");
        ET=findViewById(R.id.edit_default_dir);
        ET.setText(getData("CurrentPath"));
        if(getData("option").equals(""))
            setData("option","none");
        ET=findViewById(R.id.edit_move_dir);
        moveDir=getData("moveDir");
        if(moveDir.equals("")){
            moveDir=Environment.getExternalStorageDirectory().getPath()+"/backupFile/";//默认路径
            new File(moveDir).mkdirs();
        }
        switch(getData("option")){
            case "none":
                RG.check(R.id.radio_button_none);
                setEditTextEnable(ET,false);
                break;
            case "move":
                RG.check(R.id.radio_button_move);
                ET.setText(moveDir);
                setEditTextEnable(ET,true);
                break;
            case "dele":
                RG.check(R.id.radio_button_dele);
                setEditTextEnable(ET,false);
                break;
            default:
                RG.check(R.id.radio_button_none);
        }
    }
    public void createListener(){
        Button button_capture,button_system_camera,button_save;
        button_capture=findViewById(R.id.button_capture);
        button_system_camera=findViewById(R.id.button_system_camera);
        button_save=findViewById(R.id.button_save);
        button_capture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                button_capture_OnClick(view);
            }
        });
        button_system_camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                button_system_camera_OnClick(view);
            }
        });
        button_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                button_save_OnClick(view);
            }
        });
        RG.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                ET=findViewById(R.id.edit_move_dir);
                //Toast.makeText(MainActivity.this,i+"",Toast.LENGTH_SHORT).show();
                switch(i){
                    case R.id.radio_button_move:
                        setEditTextEnable(ET,true);
                        moveDir=getData("moveDir");
                        if(moveDir.equals("")){
                            moveDir=Environment.getExternalStorageDirectory().getPath()+"/backupFile/";//默认路径
                            new File(moveDir).mkdirs();
                        }
                        ET.setText(moveDir);
                        break;
                    default:
                        ET.setText("");
                        setEditTextEnable(ET,false);
                        break;
                }
            }
        });
    }
    public void setEditTextEnable(EditText E,boolean enable){
        E.setCursorVisible(enable);
        E.setFocusable(enable);
        E.setFocusableInTouchMode(enable);
        E.requestFocus();
        return;
    }
}